package org.dydl.common.security.impl;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

public class LogoutSuccessHandlerImpl extends AbstractAuthenticationTargetUrlRequestHandler
		implements LogoutSuccessHandler {

	private static final String HEADER_SECURITY_TOKEN = "X-AuthToken";

//	@Value("${login.url}")
	private String loginUrl="/public/login.html";

	// @Autowired
	// private IAuthTokenService authTokenService;

	// @Autowired
	// private AuthTokenGeneratorService authTokenGeneratorService;

	public void onLogoutSuccess(HttpServletRequest arg0, HttpServletResponse arg1, Authentication arg2)
			throws IOException, ServletException {
		deleteAuthenticationToken(arg0);
		PrintWriter out = arg1.getWriter();
		out.println("<html>");
		out.println("<script>");
		out.println("window.open('" + loginUrl + "','_top');");
		out.println("</script>");
		out.println("</html>");
		arg1.setContentType("text/html;charset=UTF-8");
		arg1.getWriter().flush();
	}

	private void deleteAuthenticationToken(HttpServletRequest request) {
		String token = request.getHeader(HEADER_SECURITY_TOKEN);
		if (null == token || token.trim().length() == 0) {
			return;
		}

		// String[] tokens = authTokenGeneratorService.decode(token);
		// authTokenService.deleteByTokenAndSeries(tokens[0], tokens[1]);

	}
}